package com.qying.code;

import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

public class TimeTest {

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

//        Date targetDate = sdf.parse("2021-07-26 17:37:20");
        Date targetDate = null;
        List<Date> list = new ArrayList<>();
        Date date1 = sdf.parse("2021-07-26 17:36:20");
        Date date2 = sdf.parse("2021-07-26 17:37:40");
        Date date3 = sdf.parse("2021-07-26 17:34:20");
        Date date4 = sdf.parse("2021-07-26 17:33:20");
        list.add(date1);
        list.add(date2);
        list.add(date3);
        list.add(date4);
        Date recentlyTime = findRecentlyTime(targetDate, list);
        System.out.println(recentlyTime);

    }


    public static Date findRecentlyTime(Date target, List<Date> dates){

        if (Objects.isNull(target) || CollectionUtils.isEmpty(dates)) {
            return null;
        }

        long recentlyTimeGap = Long.MAX_VALUE;
        Date recentlyDate = null;
        long targetTime = target.getTime();
        for (Date date : dates) {
            long tempGap = targetTime - date.getTime();
            if (tempGap > 0 && recentlyTimeGap > tempGap) {
                recentlyTimeGap = tempGap;
                recentlyDate = date;
            } else if(tempGap < 0 && recentlyTimeGap > -tempGap) {
                recentlyTimeGap = tempGap;
                recentlyDate = date;
            }
        }

        return recentlyDate;
    }
}
